package com.StarStudio.Controller;

import com.StarStudio.Service.CouponsService;
import com.StarStudio.Service.MinIOFileService;
import com.StarStudio.Utils.QueryPageUtils;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.Entity.*;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.file.FileTypeUtils;
import com.ruoyi.common.core.utils.file.MimeTypeUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/coupons")
@Api(tags = "优惠券接口")
public class CouponsController {

    @Autowired
    CouponsService couponsService;

    @Autowired
    private MinIOFileService minIOFileService;

    /**
     * 条件查询 优惠券分页接口
     * @param coupons 优惠券对象
     * @return 分页结果对象 PageResult
     */
    @GetMapping("/page")
    @ApiOperation("优惠券分页接口 -> 支持条件检索，检索条件封装在优惠券对象Coupons中。如需分页，必传pageNum和pageSize")
    public PageResult page(Coupons coupons){
        QueryPageUtils.startPage();
        PageInfo pageInfo;
        List<Coupons> couponsList;
        long allRecordNumber;
        try {
            couponsList = couponsService.findCouponsList(coupons);
            allRecordNumber = couponsService.findAllRecordNumber();
            pageInfo = new PageInfo<>(couponsList);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PAGE_FAIL);
        }
        return new PageResult(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PAGE_SUCCESS, pageInfo.getTotal(),couponsList,allRecordNumber);
    }

    /**
     * 获取优惠券简要信息集合
     * @return 结果对象 Result
     */
    @GetMapping("/choose_info")
    @ApiOperation("获取优惠券简要信息集合接口 -> 简要信息包括优惠券ID、优惠券名称、优惠券概览图片地址、抢购优惠券可添加的最大库存")
    public Result getCouponsChooseResultList(){
        List<CouponsChooseResult> couponsChooseResults;
        try {
            couponsChooseResults =  couponsService.getCouponsChooseResultList();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.GET_COUPONS_INFO_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.GET_COUPONS_INFO_SUCCESS,couponsChooseResults);
    }


    /**
     * 导出优惠券信息到 Excel表格
     * @param response http响应
     * @param coupons 优惠券对象
     */
    @Log(title = "优惠券管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("优惠券Excel导出接口 -> 支持条件检索，检索条件封装在优惠券对象Coupons中")
    public void export(HttpServletResponse response, Coupons coupons) {
        List<Coupons> list = couponsService.findCouponsList(coupons);
        ExcelUtil<Coupons> util = new ExcelUtil<>(Coupons.class);
        util.exportExcel(response, list, "优惠券数据");
    }

    /**
     * 根据优惠券ID删除优惠券（可单个删除也可批量删除）
     * @param Ids 待删除的优惠券ID
     * @return 结果对象 Result
     */
    @Log(title = "优惠券管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{Ids}")
    @ApiOperation("根据优惠券ID删除优惠券接口 -> 可单个删除也可批量删除，path传优惠券ID数组")
    public Result deleteCoupons(@PathVariable Long[] Ids){
        if (Ids == null || Ids.length == 0){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            if (Ids.length > 1){
                for (Long id : Ids) {
                    couponsService.DeleteCouponsById(id);
                }
            }else {
                couponsService.DeleteCouponsById(Ids[0]);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.DELETE_COUPONS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.DELETE_COUPONS_SUCCESS);
    }

    /**
     * 优惠券概览图片上传
     * @param file 文件对象
     * @return 结果对象 Result
     */
    @Log(title = "优惠券管理", businessType = BusinessType.IMPORT)
    @PostMapping("/mainPicture")
    @ApiOperation("优惠券概览图片上传接口 -> 文件名为file")
    public Result mainPicture(MultipartFile file) {
        if (file.isEmpty()){
            return new Result(HttpStatusCode.ERROR, MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        String extension = FileTypeUtils.getExtension(file);
        if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
            return new Result(HttpStatusCode.ERROR,"文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
        }
        Result upload = minIOFileService.upload(new MultipartFile[]{file});
        if (upload == null || upload.getObject() == null) {
            return new Result(HttpStatusCode.ERROR,"文件服务异常，请联系管理员");
        }
        String url = upload.getObject().toString().replace("[","").replace("]","");
        return new Result(HttpStatusCode.SUCCESS, MessageConstant.UPLOAD_IMAGE_SUCCESS, url);
    }

    /**
     * 新增优惠券
     * @param coupons 优惠券对象
     * @return 结果对象 Result
     */
    @Log(title = "优惠券管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("优惠券新增接口 -> 优惠券名称、星级、库存、商品价格（鲜豆）、市场价（人民币）不能为空")
    public Result addCoupons(@RequestBody Coupons coupons){
        if (coupons == null || StringUtils.isEmpty(coupons.getCoupon_name()) || coupons.getStock() == null
            || coupons.getStar() == null || coupons.getCoupon_price() == null || coupons.getMarket_price() == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            couponsService.addCoupons(coupons);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.ADD_COUPONS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.ADD_COUPONS_SUCCESS);
    }

    /**
     * 修改优惠券
     * @param coupons 优惠券对象
     * @return 结果对象 Result
     */
    @Log(title = "优惠券管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("优惠券修改接口 -> 优惠券ID、优惠券名称、星级、库存、商品价格（鲜豆）、市场价（人民币）不能为空")
    public Result updateCoupons(@RequestBody Coupons coupons){
        if (coupons == null || coupons.getCoupon_id() == null || StringUtils.isEmpty(coupons.getCoupon_name()) || coupons.getStock() == null
                || coupons.getStar() == null || coupons.getCoupon_price() == null || coupons.getMarket_price() == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            couponsService.updateCoupons(coupons);
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().contains(MessageConstant.REDUCE_STOCK_ACTION_ERROR)){
                return new Result(HttpStatusCode.ERROR,MessageConstant.REDUCE_STOCK_ACTION_ERROR);
            }
            return new Result(HttpStatusCode.ERROR,MessageConstant.UPDATE_COUPONS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.UPDATE_COUPONS_SUCCESS);
    }

    /**
     * 根据字符串模糊匹配商家名称
     * @param name 匹配字符串
     * @return 结果对象 Result
     */
    @GetMapping("/store_name/{name}")
    @ApiOperation("根据字符串模糊匹配商家名称接口 -> 必传name")
    public Result getLikeStoreNames(@PathVariable String name){
        if (StringUtils.isEmpty(name)){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        List<String> list;
        try {
            list = couponsService.findLikeStoreName(name);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.GET_STORE_NAMES_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.GET_STORE_NAMES_SUCCESS,list);
    }
}
